import {
	requset_url,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/config';
import {
	toUserLogin,
	checkLogin
} from '@/libs/loginuser';
import store from '@/store';

import {
	toLogin
} from '@/libs/login';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
    
	let http = requset_url,header = HEADER
	if (params != undefined) {
		header = HEADERPARAMS;
	}
	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.user_token && !checkLogin()) {
			toUserLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}
	// if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
    
	if (store.state.app.user_token) data[TOKENNAME] = store.state.app.user_token;
	return new Promise((reslove, reject) => {
		// console.log('url',http + url)
		uni.request({
			url: http + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				// console.log('res',res)
                
                // 获取支付签名的接口返回的是json数据
                if(typeof res.data === 'string'){
                    res.data = JSON.parse(res.data)
                    
                }
                
				if(noVerify){
					reslove(res.data, res);
				}
				else if (res.data.code == 900 || res.data.status == 'success'){
					reslove(res.data, res);
				}
				else if (res.data.code == 300){
					toUserLogin();
					reject(res.data);
				}
				else if (res.data.code == 301){
					reject(res.data.msg || '参数错误');
				}
				else {
					reject(res.data.msg || '系统错误');
				}
			},
			fail: (msg) => {
				console.log('msg',msg)
				reject('请求失败');
			}
		})
	});
}
const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;